package com.sun.kamun.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    public static final String ORDER_QUEUE = "order_queue";
    public static final String ORDER_EXCHANGE = "order_exchange";
    public static final String ORDER_ROUTING = "order_routing";
    public static final String DEAD_LETTER_QUEUE = "dead_letter_queue";
    public static final String DEAD_LETTER_EXCHANGE = "dead_letter_exchange";
    public static final String DEAD_LETTER_ROUTING = "dead_letter_routing";

    /**
     * 订单交换机
     */
    @Bean("orderExchange")
    public DirectExchange getOrderExchange() {
        return new DirectExchange(ORDER_EXCHANGE);
    }

    /**
     * 订单队列
     */
    @Bean("orderQueue")
    public Queue getOrderQueue() {
        return QueueBuilder.durable(ORDER_QUEUE)
                .withArgument("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE)
                .withArgument("x-dead-letter-routing-key", DEAD_LETTER_ROUTING)
                .build();
    }

    /**
     * 订单交换机与订单队列绑定
     */
    @Bean
    public Binding orderExchangeBinding(
            @Qualifier("orderExchange") DirectExchange exchange,
            @Qualifier("orderQueue") Queue queue
    ) {
        return BindingBuilder.bind(queue).to(exchange).with(ORDER_ROUTING);
    }

    /**
     * 死信交换机
     */
    @Bean("deadLetterExchange")
    public DirectExchange getDeadLetterExchange() {
        return new DirectExchange(DEAD_LETTER_EXCHANGE);
    }

    /**
     * 死信队列
     */
    @Bean("deadLetterQueue")
    public Queue getDeadLetterQueue() {
        return new Queue(DEAD_LETTER_QUEUE);
    }

    /**
     * 死信交换机与死信队列绑定
     */
    @Bean
    public Binding deadLetterExchangeBinding(
            @Qualifier("deadLetterExchange") DirectExchange exchange,
            @Qualifier("deadLetterQueue") Queue queue
    ) {
        return BindingBuilder.bind(queue).to(exchange).with(DEAD_LETTER_ROUTING);
    }
}
